﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using Microsoft.VisualBasic;
using System.Collections;
using ESRI.ArcGIS.esriSystem;
using Microsoft.VisualC.StlClr;
using System.IO;
using ESRI.ArcGIS.GeoAnalyst;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.SpatialAnalyst;


namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /*************/
        /*变量*/
        private string MouseTool = "";//tool & axmapcontrol
        private Color pcolor = Color.Black;//tool 颜色选择 & picturebox
        private int pSize = 5;//tool combobox
        IFeatureSelection pFeatureSelection = null;
        private Hashtable selectlayer = new Hashtable();//储存矢量图层
        private Hashtable Paster_selectlayer = new Hashtable();//储存栅格图层
        private bool editstart = false;
        private enum ColorOrWidthchangSize {colorchanged,sizechanged,nochanged };//枚举要素变化类型 三种：改变颜色 改变大小 聚焦（选定）      
        string out_filePath = null;
        /**************/

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Text = "5";
            pictureBox1.BackColor = Color.Black;
        }
        /*************/
        /*方法集合*/
        private void ToolStripComboBoxadd(ToolStripComboBox ToolStripComboBox)//combobox添加方法 受ToolStripComboBox调用
        {
            selectlayer.Clear();
            ToolStripComboBox.Items.Clear();
            int layernum = axMapControl1.LayerCount;
            for (int i = 0; i < layernum; i++)
            {
                IFeatureLayer pFeatureLayer;

                pFeatureLayer = axMapControl1.Map.get_Layer(i) as IFeatureLayer;
                if (pFeatureLayer != null)
                {
                    string str = axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name;
                    ToolStripComboBox.Items.Add(str);
                    
                    selectlayer.Add(str, i);
                }
                
                //LayertoNum.Add(axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name, i);
            }

        }
        private IFeatureSelection SelectSelection(ToolStripComboBox toolStripComboBox, IQueryFilter pQueryFilter)//获取要素选定区域
        {
            IFeatureSelection pFeatureSelection;
            int layer = (int)selectlayer[toolStripComboBox.Text];

            pFeatureSelection = axMapControl1.Map.get_Layer(layer) as IFeatureSelection;
            pFeatureSelection.SelectFeatures(pQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
            return pFeatureSelection;
        }
        private IGeometryCollection SelectIGeometry(ToolStripComboBox toolStripComboBox, string str)//从图层中获取Geometry集
        {


            IFeatureClass pFeatureClass;
            IFeatureLayer pFeatureLayer;
            IFeatureCursor pFeatureCursor;
            IQueryFilter pQueryFilter;
            int layer = new int();
            layer = (int)selectlayer[toolStripComboBox.Text];
            pFeatureLayer = axMapControl1.Map.get_Layer(layer) as IFeatureLayer;
            pFeatureClass = pFeatureLayer.FeatureClass;
            pQueryFilter = new QueryFilterClass();
            pQueryFilter.WhereClause = str;
            pFeatureCursor = pFeatureClass.Search(pQueryFilter, false);
            IFeature pFeature;
            IGeometry geometryBag = new GeometryBagClass();

            IGeometryCollection geometryCollection = geometryBag as IGeometryCollection;
            pFeature = pFeatureCursor.NextFeature();

            do
            {
                object missing = Type.Missing;
                geometryCollection.AddGeometry(pFeature.Shape, ref missing, ref missing);
                pFeature = pFeatureCursor.NextFeature();
              
            } while (pFeature != null);

          
            return geometryCollection;
        }
        private void DeleteSelection()//消除要素选定
        {
            if (pFeatureSelection != null)
            {
                pFeatureSelection.Clear();
            }
            axMapControl1.Refresh();
        }   
        private void ColorAndwidthrefresh(ColorOrWidthchangSize ChangeType)//要素变化类型 三种：改变颜色 改变大小 聚焦（选定） 实现方法
        {
            IGeoFeatureLayer pGeoFeatureLayer;
            ISimpleRenderer pSimpleRenderer;
            IFillSymbol pFillSymbol;
            ILineSymbol pLineSymbol;
            IRgbColor pRgbColor;
            IRgbColor pOldRgbColor;
            ISimpleMarkerSymbol pMakerSymbol;
            int layer = new int();
            layer = (int)selectlayer[toolStripComboBox7.Text];
            pGeoFeatureLayer = axMapControl1.get_Layer(layer) as IGeoFeatureLayer;           
            if (pGeoFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
            {
                pSimpleRenderer = (ISimpleRenderer)pGeoFeatureLayer.Renderer;              
                pFillSymbol = (IFillSymbol)pSimpleRenderer.Symbol;
                pLineSymbol = pFillSymbol.Outline;
                pOldRgbColor = (RgbColor)pFillSymbol.Color;
                if(ChangeType== ColorOrWidthchangSize.nochanged)
                {
                    comboBox1.Text = pLineSymbol.Width.ToString();
                }
                else
                {
                    pRgbColor = new RgbColorClass();
                    pRgbColor.Red = Color.Black.R;//颜色
                    pRgbColor.Green = Color.Black.G;
                    pRgbColor.Blue = Color.Black.B;
                    pLineSymbol.Color = pRgbColor;
                    if(ChangeType == ColorOrWidthchangSize.colorchanged)
                    {
                        pRgbColor.Red = pcolor.R;//颜色
                        pRgbColor.Green = pcolor.G;
                        pRgbColor.Blue = pcolor.B;
                    }
                    else
                    {
                        pRgbColor = pOldRgbColor;
                    }
                   
                    pLineSymbol.Width = double.Parse(comboBox1.Text);
                    pFillSymbol.Color = pRgbColor;
                    pFillSymbol.Outline = pLineSymbol;
                    pSimpleRenderer.Symbol = pFillSymbol as ISymbol;
                    pGeoFeatureLayer.Renderer = pSimpleRenderer as IFeatureRenderer;
                    axMapControl1.Refresh();
                }
                //comboBox1.Text = pLineSymbol.Width.ToString();
               
            }
            if (pGeoFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
            {
                pSimpleRenderer = (ISimpleRenderer)pGeoFeatureLayer.Renderer;

                pLineSymbol = (ILineSymbol)pSimpleRenderer.Symbol;
                pOldRgbColor = (RgbColor)pLineSymbol.Color;
                if (ChangeType == ColorOrWidthchangSize.nochanged)
                {
                    comboBox1.Text = pLineSymbol.Width.ToString();
                }
                else
                {
                    pRgbColor = new RgbColorClass();
                    if (ChangeType == ColorOrWidthchangSize.colorchanged)
                    {
                        pRgbColor.Red = pcolor.R;//颜色
                        pRgbColor.Green = pcolor.G;
                        pRgbColor.Blue = pcolor.B;
                    }
                    else
                    {
                        pRgbColor = pOldRgbColor;
                    }
                    pLineSymbol.Width = double.Parse(comboBox1.Text);
                    pLineSymbol.Color = pRgbColor;
                    pSimpleRenderer.Symbol = pLineSymbol as ISymbol;
                    pGeoFeatureLayer.Renderer = pSimpleRenderer as IFeatureRenderer;
                    axMapControl1.Refresh();
                }
                //comboBox1.Text = pLineSymbol.Width.ToString();
            }
            if (pGeoFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
            {
                pSimpleRenderer = (ISimpleRenderer)pGeoFeatureLayer.Renderer;
                pMakerSymbol = (ISimpleMarkerSymbol)pSimpleRenderer.Symbol;
                pOldRgbColor = (RgbColor)pMakerSymbol.Color;
                if (ChangeType == ColorOrWidthchangSize.nochanged)
                {
                    comboBox1.Text = pMakerSymbol.Size.ToString();
                }
                else
                {
                    pRgbColor = new RgbColorClass();
                    if (ChangeType == ColorOrWidthchangSize.colorchanged)
                    {
                        pRgbColor.Red = pcolor.R;//颜色
                        pRgbColor.Green = pcolor.G;
                        pRgbColor.Blue = pcolor.B;
                    }
                    else
                    {
                        pRgbColor = pOldRgbColor;
                    }
                    pMakerSymbol.Color = pRgbColor;
                    pMakerSymbol.Size = double.Parse(comboBox1.Text);
                    pSimpleRenderer.Symbol = pMakerSymbol as ISymbol;
                    pGeoFeatureLayer.Renderer = pSimpleRenderer as IFeatureRenderer;
                    axMapControl1.Refresh();
                }
                //comboBox1.Text = psimpleMarkerSymbol.Size.ToString();
                
            }

        }       
        private void SetStretchColorRampRenderer(IRasterLayer pRasterLayer)//栅格图层编辑
        {
            //创建RasterStretchColorRampRendererClass对象
            IRasterStretchColorRampRenderer pRStretchRender = new RasterStretchColorRampRendererClass();
            //QI到IRasterRenderer
            IRasterRenderer pRasterRender = pRStretchRender as IRasterRenderer; pRasterRender.Raster = pRasterLayer as IRaster; pRasterRender.Update();
            //创建两个起始颜色
            IRgbColor pFromRgbColor = new RgbColorClass(); pFromRgbColor.Red = 255;
            IRgbColor pToRgbColor = new RgbColorClass();
            pToRgbColor.Blue = 255;         //创建起止颜色带
            IAlgorithmicColorRamp pAlgorithmicColorRamp = new AlgorithmicColorRampClass(); pAlgorithmicColorRamp.Size = 255; pAlgorithmicColorRamp.FromColor = pFromRgbColor as IColor; pAlgorithmicColorRamp.ToColor = pToRgbColor as IColor;
            bool btrue = true; pAlgorithmicColorRamp.CreateRamp(out btrue);
            //选择拉伸颜色带符号化的波段
            pRStretchRender.BandIndex = 0;
            //设置拉伸颜色带符号化所采用的颜色带
            pRStretchRender.ColorRamp = pAlgorithmicColorRamp as IColorRamp;
            pRasterRender.Update();
            //符号化RasterLayer
            pRasterLayer.Renderer = pRasterRender;
            axMapControl1.Refresh();
        }
        public string OpenFileorFold(string FoldOrFile)//打开文件 当FoldOrFile="openfold"打开文件夹，其余打开对应文件
        {
            if (FoldOrFile == "openfold")
            {
                string foldpath = "";
                System.Windows.Forms.FolderBrowserDialog openFileDialogfold = new System.Windows.Forms.FolderBrowserDialog();
                openFileDialogfold.Description = "请选择所在文件夹";

                if (openFileDialogfold.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foldpath = openFileDialogfold.SelectedPath;
                }
                else
                {
                    MessageBox.Show("路径为空");
                }
                return foldpath;
            }
            else
            {
                string Filepath = "";
                System.Windows.Forms.OpenFileDialog openFileDialog;
                openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "Open";
                openFileDialog.Filter = FoldOrFile;
                if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Filepath = openFileDialog.FileName;
                }
                else
                {
                    MessageBox.Show("路径为空");
                }
                return Filepath;
            }
        }
        private void getSelectedFeature()
        {
            try
            {
                IMap map = axMapControl1.Map;
                ISelection selection = map.FeatureSelection;
                IEnumFeatureSetup iEnumFeatureSetup = (IEnumFeatureSetup)selection;
                iEnumFeatureSetup.AllFields = true;
                IEnumFeature enumFeature = (IEnumFeature)iEnumFeatureSetup;
                enumFeature.Reset();
                IFeature feature = enumFeature.Next();
                while (feature != null)
                {
                    string hehe = feature.get_Value(5).ToString();
                    MessageBox.Show(hehe);
                    feature = enumFeature.Next();
                }
            }
            catch (Exception e)
            {
            }
        }
        /**************/

        /***********************************************/
        /*toolStrip*/
        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {           
            string Filepath = OpenFileorFold("Map Documents (.*mxd) |*.mxd");
            if (axMapControl1.CheckMxFile(Filepath))
            {
                axMapControl1.LoadMxFile(Filepath, 0, Type.Missing);

            }
            else
            {
                MessageBox.Show("打开Error");
                return;
            }
        }
        private void 打开栅格数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string Filepath = OpenFileorFold("Map Documents (.*jpg) |*.jpg");
            IRasterLayer pRasterLayer = new RasterLayerClass();
            if (Filepath != "")
            {
                pRasterLayer.CreateFromFilePath(Filepath);
                axMapControl1.AddLayer(pRasterLayer);
                axMapControl1.Refresh();
            }
            else
            {
                MessageBox.Show("未选择文件Error");              
            }
        }
        private void 打开矢量数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IWorkspaceFactory pWorkspaceFactory;
            IFeatureWorkspace pFeatureWorkspace;
            IFeatureClass pFeatureClass;
            IFeatureLayer pFeatureLayer;
            pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            string path = OpenFileorFold("openfold");
            if (path != "")
            {
                pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(path, 0) as IFeatureWorkspace;
                pFeatureClass = pFeatureWorkspace.OpenFeatureClass("New_Shapefile");
                pFeatureLayer = new FeatureLayerClass();
                pFeatureLayer.FeatureClass = pFeatureClass;
                pFeatureLayer.Name = "New_Shapefile";
                axMapControl1.AddLayer(pFeatureLayer);
                axMapControl1.Refresh();
            }
            else
            {
                MessageBox.Show("未选择文件夹");
            }
        }
        private void 放大ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IEnvelope pEnvelope;
            pEnvelope = axMapControl1.Extent;
            pEnvelope.Expand(0.5, 0.5, true);
            axMapControl1.Extent = pEnvelope;
            axMapControl1.Refresh();
        }
        private void 缩小ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IEnvelope pEnvelope;
            pEnvelope = axMapControl1.Extent;
            pEnvelope.Expand(2, 2, true);
            axMapControl1.Extent = pEnvelope;
            axMapControl1.Refresh();
        }
        private void 全图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            axMapControl1.Extent = axMapControl1.FullExtent;
        }
        private void 画点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MouseTool = "Point";
        }
        private void 画线ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MouseTool = "Line";
        }
        private void 画面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MouseTool = "Polygon";
        }
        private void 取消编辑状态ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MouseTool = "";
        }
        private void 颜色选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ColorDialog colorDia = new ColorDialog();
            //显示颜色对话框
            DialogResult dr = colorDia.ShowDialog();
            //如果选中颜色，单击“确定”按钮则改变文本框的文本颜色
            if (dr == DialogResult.OK)
            {
                pcolor = colorDia.Color;
            }
            pictureBox1.BackColor = pcolor;
        }
        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            pSize = int.Parse(comboBox1.Text);
        }
        private void pictureBox1_Click(object sender, EventArgs e)//包含要素颜色编辑
        {
            ColorDialog colorDia = new ColorDialog();
            //显示颜色对话框
            DialogResult dr = colorDia.ShowDialog();
            //如果选中颜色，单击“确定”按钮则改变文本框的文本颜色
            if (dr == DialogResult.OK)
            {
                pcolor = colorDia.Color;
            }
            pictureBox1.BackColor = pcolor;
            if(editstart==true&&toolStripComboBox7.Text!="")
            {
                ColorAndwidthrefresh(ColorOrWidthchangSize.colorchanged);

            }
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)//包含要素宽度编辑
        {
            if (editstart == true && toolStripComboBox7.Text != "")
            {
                ColorAndwidthrefresh(ColorOrWidthchangSize.sizechanged);
            }
        }
        /***************************/
        /*属性查询*/
        private void toolStripComboBox2_Click(object sender, EventArgs e)
        {
             ToolStripComboBoxadd(toolStripComboBox2);
        }
        private void 开始选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str = Interaction.InputBox("请输入表达式", "输入索引", "ID=0", 100, 100);  
            IQueryFilter pQueryFilter = new QueryFilterClass();
            pQueryFilter.WhereClause = str;
            DeleteSelection();
            pFeatureSelection = SelectSelection(toolStripComboBox2, pQueryFilter);
            //selectpfeature = pFeatureSelection as IFeature;
            pFeatureSelection.SelectionChanged();
            axMapControl1.Refresh();

        }
     
        /*属性查询*/
        /***************************/

        /*************************/
        /*位置查询*/
        private void toolStripComboBox4_Click(object sender, EventArgs e)
        {
            ToolStripComboBoxadd(toolStripComboBox4);
            toolStripComboBox4.Items.Remove(toolStripComboBox5.Text);
            /*IFeatureLayer pFeatureLayer;
             pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;
             if (pFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
             {
                         //为点图层         

             }

             if (pFeature. FeatureClass. ShapeType ==esriGeometryType.esriGeometryPloyLine)
             {
                为线图层
             }
 

             if (pFeature. FeatureClass. ShapeType ==esriGeometryType.esriGeometryPolygon)    
             {
              为面图层
             }*/
        }
        private void toolStripComboBox5_Click(object sender, EventArgs e)
        {
            ToolStripComboBoxadd(toolStripComboBox5);
            toolStripComboBox5.Items.Remove(toolStripComboBox4.Text);
        }
   
        private void 开始查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            string str = Interaction.InputBox("请输入表达式", "输入索引", "ID=0", 100, 100);
            IGeometryCollection geometryCollection = SelectIGeometry(toolStripComboBox5,str);
            ISpatialFilter pSpatialFilter = new SpatialFilter();
  
            pSpatialFilter.Geometry = geometryCollection as IGeometry;
            switch (toolStripComboBox3.Text)
            {
                case "相交":
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    break;
                case "重叠":
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelOverlaps;
                    break;
                case "包含":
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    break;
            }
            DeleteSelection();
            pFeatureSelection = SelectSelection(toolStripComboBox4, (IQueryFilter)pSpatialFilter);

           // ISelectionSet pSelectionSet = featureSelection.SelectionSet;

            axMapControl1.Refresh();
        }
        /*位置查询*/
        /*************************/


        /*************************/
        /*缓冲区分析*/
        private void toolStripComboBox6_Click(object sender, EventArgs e)
        {
            ToolStripComboBoxadd(toolStripComboBox6);
        }
        private void 选择并分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string str = Interaction.InputBox("请输入表达式", "输入索引", "ID=0", 100, 100);
           // string str = "ID = 0";
            IFeature pFeature;
            IFeatureClass pFeatureClass;
            IFeatureLayer pFeatureLayer;
            IFeatureCursor pFeatureCursor;
            IQueryFilter pQueryFilter;

            int layer = (int)selectlayer[toolStripComboBox6.Text];
            pFeatureLayer = axMapControl1.Map.get_Layer(layer) as IFeatureLayer;
            pFeatureClass = pFeatureLayer.FeatureClass;
            pQueryFilter = new QueryFilterClass();
            pQueryFilter.WhereClause =str;
            pFeatureCursor = pFeatureClass.Search(pQueryFilter, false);
            pFeature = pFeatureCursor.NextFeature();
            do
            {              
                ITopologicalOperator pTopologicalOperator;
                IPolygon pPolygon;
                pTopologicalOperator = pFeature.Shape as ITopologicalOperator;
                pPolygon = pTopologicalOperator.Buffer(float.Parse(toolStripTextBox1.Text)) as IPolygon;
                axMapControl1.DrawShape(pPolygon);
                pFeature = pFeatureCursor.NextFeature();
            } while (pFeature != null);
        }

        /*缓冲区分析*/
        /*************************/
       

        private void 取消ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSelection();
       
        }
        /*************************/
        /*矢量要素编辑*/
        private void toolStripComboBox7_Click(object sender, EventArgs e)
        {
            ToolStripComboBoxadd(toolStripComboBox7);
        }
       
        private void toolStripComboBox7_TextChanged(object sender, EventArgs e)
        {
            ColorAndwidthrefresh(ColorOrWidthchangSize.nochanged);
        }
        /*矢量要素编辑*/
        /*************************/

        private void 开始编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            editstart = true;
            ColorAndwidthrefresh(ColorOrWidthchangSize.nochanged);
            结束编辑ToolStripMenuItem.Enabled = true;
            开始编辑ToolStripMenuItem.Enabled = false;
        }
        private void endedition()
        {
            editstart = false;
            开始编辑ToolStripMenuItem.Enabled = true;
            结束编辑ToolStripMenuItem.Enabled = false;
        }
        private void 结束编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            endedition();
        }

        /*************************/
        /*栅格图层编辑*/
        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IRasterLayer pRasterLayer;
            int layer = (int)selectlayer[toolStripComboBox8.Text];

            pRasterLayer = axMapControl1.Map.get_Layer(layer) as IRasterLayer;
            SetStretchColorRampRenderer(pRasterLayer);
        }
        private void toolStripComboBox8_Click(object sender, EventArgs e)
        {
            selectlayer.Clear();
            toolStripComboBox8.Items.Clear();
            int layernum = axMapControl1.LayerCount;
            for (int i = 0; i < layernum; i++)
            {
                IRasterLayer pRasterLayer;
                pRasterLayer = axMapControl1.Map.get_Layer(i) as IRasterLayer;
                if (pRasterLayer != null)
                {
                    string str = axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name;
                    toolStripComboBox8.Items.Add(str);

                    selectlayer.Add(str, i);
                }

                //LayertoNum.Add(axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name, i);
            }
        }
        /*栅格图层编辑*/
        /*************************/

        /*************************/
        /*分级*/
        private void toolStripComboBox9_Click(object sender, EventArgs e)
        {
            ToolStripComboBoxadd(toolStripComboBox9);
        }

        private void 分级ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            endedition();
            try
            {
                int layer = (int)selectlayer[toolStripComboBox9.Text];

                IFeatureLayer pFeatLyr = axMapControl1.get_Layer(layer) as IFeatureLayer;
                //输入分级设色符号化的字段（我这里默认FID字段【高耦合,分级设色字段需为数值型】）
                string sFieldName = "FID";//要素类中数值型字段的名称
                                          //输入分级设色的数量
                int numclasses = 3;

                IGeoFeatureLayer pGeoFeatureL = pFeatLyr as IGeoFeatureLayer;
                object dataFrequency;
                object dataValues;
                bool ok;
                int breakIndex;

                ITable pTable = pGeoFeatureL.FeatureClass as ITable;
                ITableHistogram pTableHistogram = new BasicTableHistogram() as ITableHistogram;
                IBasicHistogram pBasicHistogram = (IBasicHistogram)pTableHistogram;
                pTableHistogram.Field = sFieldName;
                pTableHistogram.Table = pTable;
                pBasicHistogram.GetHistogram(out dataValues, out dataFrequency);     //获取渲染字段的值及其出现的频率
                IClassifyGEN pClassify = new EqualInterval();
                try
                {
                    pClassify.Classify(dataValues, dataFrequency, ref numclasses);  //根据获取字段的值和出现的频率对其进行等级划分 
                }
                catch { }
                //返回一个数组
                double[] Classes = pClassify.ClassBreaks as double[];
                int ClassesCount = Classes.GetUpperBound(0);
                IClassBreaksRenderer pClassBreaksRenderer = new ClassBreaksRenderer();
                pClassBreaksRenderer.Field = sFieldName; //设置分级字段
                pClassBreaksRenderer.BreakCount = ClassesCount; //设置分级数目
                pClassBreaksRenderer.SortClassesAscending = true;//分级后的图例是否按升级顺序排列
                                                                 //设置分级着色所需颜色带的起止颜色
                IHsvColor pFromColor = new HsvColor();
                pFromColor.Hue = 0;//黄色
                pFromColor.Saturation = 50;
                pFromColor.Value = 96;
                IHsvColor pToColor = new HsvColor();
                pToColor.Hue = 80;
                pToColor.Saturation = 100;
                pToColor.Value = 96;
                //产生颜色带对象
                IAlgorithmicColorRamp pAlgorithmicCR = new AlgorithmicColorRamp();
                pAlgorithmicCR.Algorithm = esriColorRampAlgorithm.esriHSVAlgorithm;
                pAlgorithmicCR.FromColor = pFromColor;
                pAlgorithmicCR.ToColor = pToColor;
                pAlgorithmicCR.Size = ClassesCount;
                pAlgorithmicCR.CreateRamp(out ok);
                //获得颜色
                IEnumColors pEnumColors = pAlgorithmicCR.Colors;
                List<esriSimpleMarkerStyle> lt = new List<esriSimpleMarkerStyle>();
                lt.Add(esriSimpleMarkerStyle.esriSMSCircle);
                lt.Add(esriSimpleMarkerStyle.esriSMSCross);
                lt.Add(esriSimpleMarkerStyle.esriSMSDiamond);
                lt.Add(esriSimpleMarkerStyle.esriSMSSquare);
                lt.Add(esriSimpleMarkerStyle.esriSMSX);
                //需要注意的是分级着色对象中的symbol和break的下标都是从0开始
                for (breakIndex = 0; breakIndex <= ClassesCount - 1; breakIndex++)
                {
                    IColor pColor = pEnumColors.Next();
                    switch (pGeoFeatureL.FeatureClass.ShapeType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                            {
                                ISimpleFillSymbol pSimpleFillS = new SimpleFillSymbol();
                               
                                pSimpleFillS.Color = pColor;
                                pSimpleFillS.Style = esriSimpleFillStyle.esriSFSSolid;
                                ISimpleRenderer pSimpleRenderer;
                                IFillSymbol pFillSymbol;
                                ILineSymbol pLineSymbol;
                                pSimpleRenderer = (ISimpleRenderer)pGeoFeatureL.Renderer;
                                pFillSymbol = (IFillSymbol)pSimpleRenderer.Symbol;
                                pLineSymbol = pFillSymbol.Outline;
                                pSimpleFillS.Outline = pLineSymbol;
                                pClassBreaksRenderer.set_Symbol(breakIndex, (ISymbol)pSimpleFillS);//设置填充符号
                                pClassBreaksRenderer.set_Break(breakIndex, Classes[breakIndex + 1]);//设定每一分级的分级断点
                                break;
                            }
                        case esriGeometryType.esriGeometryPolyline:
                            {
                                ISimpleLineSymbol pSimpleLineSymbol = new SimpleLineSymbol();
                                pSimpleLineSymbol.Color = pColor;
                                ISimpleRenderer pSimpleRenderer;
                                ILineSymbol pLineSymbol;
                                pSimpleRenderer = (ISimpleRenderer)pGeoFeatureL.Renderer;
                                pLineSymbol = (ILineSymbol)pSimpleRenderer.Symbol;
                                pSimpleLineSymbol.Width = pLineSymbol.Width;
                                pClassBreaksRenderer.set_Symbol(breakIndex, (ISymbol)pSimpleLineSymbol);
                                pClassBreaksRenderer.set_Break(breakIndex, Classes[breakIndex + 1]);
                                break;
                            }
                        case esriGeometryType.esriGeometryPoint:
                            {
                                int styletype = breakIndex;
                                if (styletype >= lt.Count)
                                {
                                    styletype -= lt.Count;
                                }
                                ISimpleMarkerSymbol pSimpleMarkerSymbol = new SimpleMarkerSymbol();
                                pSimpleMarkerSymbol.Color = pColor;
                                pSimpleMarkerSymbol.Style = lt[styletype];

                                ISimpleRenderer pSimpleRenderer;
                                ISimpleMarkerSymbol pMakerSymbol;
                                pSimpleRenderer = (ISimpleRenderer)pGeoFeatureL.Renderer;
                                pMakerSymbol = (ISimpleMarkerSymbol)pSimpleRenderer.Symbol;
                                pSimpleMarkerSymbol.Size = pMakerSymbol.Size;
                                pClassBreaksRenderer.set_Symbol(breakIndex, (ISymbol)pSimpleMarkerSymbol);//设置填充符号
                                pClassBreaksRenderer.set_Break(breakIndex, Classes[breakIndex + 1]);//设定每一分级的分级断点
                                break;
                            }
                    }
                }
                pGeoFeatureL.Renderer = (IFeatureRenderer)pClassBreaksRenderer;
                axMapControl1.Refresh();
                axTOCControl1.Update();
            }
            catch (Exception ex)
            {
                MessageBox.Show("该字段不存在或无法渲染！");
            }
            /*****************/
            /*
            pLayer = pMap.get_Layer(i);

            //-------------UniqueValueRenderer----------------------///	
            IGeoFeatureLayer pGeoFeatureLayer = pLayer as IGeoFeatureLayer;
            IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();

            pUniqueValueRenderer.FieldCount = 1;
            string FieldName = comboBox5.SelectedItem.ToString(); //*获取字段名称
            pUniqueValueRenderer.set_Field(0, FieldName);

            //可选代码，颜色差异小，颜色均为随机色，多次点击渲染会不断变色,给每一个值定义一种颜色
            //设置色谱的范围
            IRandomColorRamp pRandomColorRamp = new RandomColorRampClass();
            /*
            pRandomColorRamp.StartHue = 0;  //设置随机色带的起始色度
            pRandomColorRamp.EndHue = 360;  //设置随机色带的末尾色度
            pRandomColorRamp.MinSaturation = 10;  //设置随机色带的最小饱和度
            pRandomColorRamp.MaxSaturation = 30;  //设置随机色带的最大饱和度
            pRandomColorRamp.MinValue = 100;  //设置随机色带的最小纯度
             pRandomColorRamp.MaxValue = 100;  //设置随机色带的最大纯度
             */

            /*
            IQueryFilter pQueryFilter = new QueryFilterClass();
            pRandomColorRamp.Size = pGeoFeatureLayer.FeatureClass.FeatureCount(pQueryFilter);//根据渲染字段的唯一值的个数，设置一组随机颜色

            bool out_outparameter = false;
            pRandomColorRamp.CreateRamp(out out_outparameter);  //创建随机颜色；需要输出参数，输出参数的类型为bool

            IEnumColors pEnumRamp = pRandomColorRamp.Colors;  //创建颜色枚举
            IColor pNextUniqueColor;  //用来移动的指示颜色的指针
            pQueryFilter = new QueryFilterClass();
            pQueryFilter.AddField(FieldName); //添加待查询的字段

            ITable pTable = pLayer as Table;
            int FieldNumbero = pTable.FindField(FieldName);  //将字段在表中的索引(第几列)存储到FieldNumbero

            ICursor pCursor = pTable.Search(pQueryFilter, true);
            IRow pNextRow = pCursor.NextRow();
            IRowBuffer pNextRowBuffer = null;
            object codeValue = null;  //创建移动指针，用来指向要渲染字段的每一个值

            while (pNextRow != null)
            {
                pNextRowBuffer = pNextRow as RowBuffer;
                codeValue = pNextRowBuffer.get_Value(FieldNumbero);  //获取要渲染字段的每一个值
                pNextUniqueColor = pEnumRamp.Next();  //将pNextUniqueColor指向之前创建好的色带pEnumRamp的下一个颜色

                //若为空值返回色带的第一个颜色进行赋值
                if (pNextUniqueColor == null)
                {
                    pEnumRamp.Reset();  //跳回pEnumRamp顶部
                    pNextUniqueColor = pEnumRamp.Next();
                }
                ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbolClass();
                pSimpleFillSymbol.Color = pNextUniqueColor;
                pUniqueValueRenderer.AddValue(codeValue.ToString(), "", pSimpleFillSymbol as ISymbol);
                pNextRow = pCursor.NextRow();
            }
            pGeoFeatureLayer.Renderer = pUniqueValueRenderer as IFeatureRenderer;
            //-----------------------------------------------/

            axMapControl1.Extent = axMapControl1.FullExtent;
            axMapControl1.ActiveView.Refresh();
            axTOCControl1.Update();

            MessageBox.Show("唯一值渲染成功!");
            */
            /*****************/
        }
        /*分级*/

        /*点密度图*/
        private void 点密度图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int layer = (int)selectlayer[toolStripComboBox9.Text];
            IGeoFeatureLayer pLayer = this.axMapControl1.get_Layer(layer) as IGeoFeatureLayer;
            ITable pTable = pLayer.FeatureClass as ITable;
            IQueryFilter pQueryFilter = new QueryFilterClass();
            pQueryFilter.AddField("PERIMETER");
            ICursor pCursor = pTable.Search(pQueryFilter, true);
            IDataStatistics pDataStatistics = new DataStatisticsClass();
            pDataStatistics.Cursor = pCursor;//数据来源
            pDataStatistics.Field = "PERIMETER";
            IStatisticsResults pStatisticsResult = pDataStatistics.Statistics;
            double Dvalues = (pStatisticsResult.Minimum + pStatisticsResult.Maximum) / 10;//根据情况而定

            IDotDensityRenderer pDotDensityRenderer = new DotDensityRendererClass();

            IRendererFields pRendererField = pDotDensityRenderer as IRendererFields;
            pRendererField.AddField("PERIMETER", "PERIMETER");

            IDotDensityFillSymbol pDotDensityFillSymbol = new DotDensityFillSymbolClass();
            pDotDensityFillSymbol.DotSize = 5;
            IRgbColor GetRgbColor = new RgbColorClass();

            /*ISimpleRenderer pSimpleRenderer;
            IFillSymbol pFillSymbol;
            pSimpleRenderer = (ISimpleRenderer)pLayer.Renderer;
            pFillSymbol = (IFillSymbol)pSimpleRenderer.Symbol;*/
            GetRgbColor.Red = Color.Yellow.R;
            GetRgbColor.Green = Color.Yellow.G;
            GetRgbColor.Blue = Color.Yellow.B;
            pDotDensityFillSymbol.BackgroundColor = GetRgbColor;
            GetRgbColor.Red = 255;
            GetRgbColor.Green = 200;
            GetRgbColor.Blue = 0;
            pDotDensityFillSymbol.Color = GetRgbColor;

            ISymbolArray pSymbolArray = pDotDensityFillSymbol as ISymbolArray;
            ISimpleMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbolClass();
            GetRgbColor.Red = 255;
            GetRgbColor.Green = 0;
            GetRgbColor.Blue = 0;
            pMarkerSymbol.Color = GetRgbColor;
            pMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSSquare;
            pMarkerSymbol.Size = 5;
            pSymbolArray.AddSymbol(pMarkerSymbol as ISymbol);

            pDotDensityRenderer.DotDensitySymbol = pDotDensityFillSymbol;
            pDotDensityRenderer.DotValue = Dvalues;
            pDotDensityRenderer.CreateLegend();

            pLayer.Renderer = pDotDensityRenderer as IFeatureRenderer;
            this.axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            this.axTOCControl1.Update();

        }


        /*点密度图*/
        /*************************/
        private void 唯一值ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int layer = (int)selectlayer[toolStripComboBox9.Text];
            IGeoFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(layer) as IGeoFeatureLayer;
            try
            {
                //创建UniqueValueRenderClass对象
                IUniqueValueRenderer pUVRender = new UniqueValueRendererClass();
                ISimpleMarkerSymbol pSimpleMarkerSymbol;
                ISimpleMarkerSymbol pSimpleMarkerSymbol2;
                ISimpleMarkerSymbol pSimpleMarkerSymbol3;
                IRgbColor pRgbColor;

                pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                pSimpleMarkerSymbol2 = new SimpleMarkerSymbolClass();
                pSimpleMarkerSymbol3 = new SimpleMarkerSymbolClass();

                pRgbColor = new RgbColorClass();
                pRgbColor.Red = 255;
                pSimpleMarkerSymbol.Color = pRgbColor;
                pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSDiamond;
                pUVRender.AddValue("0", "one", pSimpleMarkerSymbol as ISymbol);

                pRgbColor = new RgbColorClass();
                pRgbColor.Green = 255;
                pSimpleMarkerSymbol2.Color = pRgbColor;
                pSimpleMarkerSymbol2.Style = esriSimpleMarkerStyle.esriSMSCircle;
                pUVRender.AddValue("1", "two", pSimpleMarkerSymbol2 as ISymbol);

                pRgbColor = new RgbColorClass();
                pRgbColor.Blue = 255;
                pSimpleMarkerSymbol3.Color = pRgbColor;
                pSimpleMarkerSymbol3.Style = esriSimpleMarkerStyle.esriSMSSquare;
                pUVRender.AddValue("2", "three", pSimpleMarkerSymbol3 as ISymbol);


                pUVRender.FieldCount = 1;
                pUVRender.set_Field(0, "类型");
                IGeoFeatureLayer pGFeatureLyr = pFeatureLayer as IGeoFeatureLayer;
                pGFeatureLyr.Renderer = pUVRender as IFeatureRenderer;
            }
            catch (Exception Err)
            {
                MessageBox.Show(Err.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }



        /*toolStrip*/
        /***********************************************/



        /***********************************************   
        axMapControl1*/
        /*功能*/
        private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e)
        {
            if(MouseTool == "")
            {
                MouseTool = "movemap";
            }
            if(MouseTool=="movemap")
            { 
            axMapControl1.MousePointer = esriControlsMousePointer.esriPointerPan;
            axMapControl1.Pan();
            }
            if(MouseTool=="Point")
            {
                IElement pElement;
                IMarkerElement pMarkerElement;
                ISimpleMarkerSymbol pSimpleMarkerSymbol;
                IRgbColor pRgbColor;
                pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                pRgbColor = new RgbColorClass();
                pSimpleMarkerSymbol.Size = pSize;
                pRgbColor.Red = pcolor.R;//颜色
                pRgbColor.Green = pcolor.G;
                pRgbColor.Blue = pcolor.B;
                pSimpleMarkerSymbol.Color = pRgbColor;
                //pSimpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSDiamond;
                pMarkerElement = new MarkerElementClass();
                pMarkerElement.Symbol = pSimpleMarkerSymbol;
                pElement = new MarkerElement();
                pElement = pMarkerElement as IElement;
                pElement.Geometry = axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                IGraphicsContainer pGraphicsContainer = axMapControl1.ActiveView.FocusMap as IGraphicsContainer;
                pGraphicsContainer.AddElement(pElement, 0);
                axMapControl1.ActiveView.Refresh();
                /*
                ISimpleMarkerSymbol pSimpleMarkerSymbol;
                IRgbColor pRgbColor;
                IRubberBand pRubberBand;
                IPoint pPoint;           
                pSimpleMarkerSymbol = new SimpleMarkerSymbolClass();
                pRgbColor = new RgbColorClass();
                pSimpleMarkerSymbol.Size = pSize;
                pRgbColor.Red = pcolor.R;//颜色
                pRgbColor.Green = pcolor.G;
                pRgbColor.Blue = pcolor.B;
                pSimpleMarkerSymbol.Color = pRgbColor;
                pRubberBand = new RubberPointClass();
                pPoint = pRubberBand.TrackNew(axMapControl1.ActiveView.ScreenDisplay, pSimpleMarkerSymbol as ISymbol) as IPoint;
                axMapControl1.ActiveView.ScreenDisplay.StartDrawing(axMapControl1.ActiveView.ScreenDisplay.hDC, (short)esriScreenCache.esriNoScreenCache);
                axMapControl1.ActiveView.ScreenDisplay.SetSymbol(pSimpleMarkerSymbol as ISymbol);
                axMapControl1.ActiveView.ScreenDisplay.DrawPoint(pPoint);
                axMapControl1.ActiveView.ScreenDisplay.FinishDrawing();
                */
            }
            if(MouseTool == "Line")
            {
                ISimpleLineSymbol pSimpleLineSymbol;
                IRgbColor pRgbColor;
                pSimpleLineSymbol = new SimpleLineSymbolClass();
                pRgbColor = new RgbColorClass();
                pSimpleLineSymbol.Width = pSize;
                pRgbColor.Red = pcolor.R;//颜色
                pRgbColor.Green = pcolor.G;
                pRgbColor.Blue = pcolor.B;
                pSimpleLineSymbol.Color = pRgbColor;
                IGeometry polyline;
                polyline = axMapControl1.TrackLine();
                ILineElement pLineElement;
                pLineElement = new LineElementClass();
                pLineElement.Symbol = pSimpleLineSymbol;
                IElement pElement;
                pElement = pLineElement as IElement;
                pElement.Geometry = polyline;
                IGraphicsContainer pGraphicsContainer = axMapControl1.ActiveView.FocusMap as IGraphicsContainer;
                pGraphicsContainer.AddElement((IElement)pLineElement, 0);
                axMapControl1.ActiveView.Refresh();

                /*
                ISimpleLineSymbol pSimpleLineSymbol;
                IRgbColor pRgbColor;
                IRubberBand pRubberBand;
                IPolyline pPloyline;
                pSimpleLineSymbol = new SimpleLineSymbolClass();
                pRgbColor = new RgbColorClass();
                pRgbColor.Red = pcolor.R;//颜色
                pRgbColor.Green = pcolor.G;
                pRgbColor.Blue = pcolor.B;
                pSimpleLineSymbol.Width = pSize;
                pSimpleLineSymbol.Color = pRgbColor;
                pRubberBand = new RubberLineClass();
                pPloyline = pRubberBand.TrackNew(axMapControl1.ActiveView.ScreenDisplay, pSimpleLineSymbol as ISymbol) as IPolyline;
                axMapControl1.ActiveView.ScreenDisplay.StartDrawing(axMapControl1.ActiveView.ScreenDisplay.hDC, (short)esriScreenCache.esriNoScreenCache);
                axMapControl1.ActiveView.ScreenDisplay.SetSymbol(pSimpleLineSymbol as ISymbol);
                axMapControl1.ActiveView.ScreenDisplay.DrawPolyline(pPloyline);
                axMapControl1.ActiveView.ScreenDisplay.FinishDrawing();*/

            }
            if(MouseTool == "Polygon")
            {
                ISimpleFillSymbol pSimpleFillSymbol;
                IRgbColor pRgbColor;
                pSimpleFillSymbol = new SimpleFillSymbolClass();
                pRgbColor = new RgbColorClass();
                pRgbColor.Red = pcolor.R;//颜色
                pRgbColor.Green = pcolor.G;
                pRgbColor.Blue = pcolor.B;
                pSimpleFillSymbol.Color = pRgbColor;


                IGeometry Polygon;
                Polygon = axMapControl1.TrackPolygon();
                IPolygonElement PolygonElement;
                PolygonElement = new PolygonElementClass();
                IElement pElement;
                pElement = PolygonElement as IElement;
                pElement.Geometry = Polygon;
              
                IGraphicsContainer pGraphicsContainer = axMapControl1.ActiveView.FocusMap as IGraphicsContainer;
                pGraphicsContainer.AddElement((IElement)PolygonElement, 0);
                axMapControl1.ActiveView.Refresh();
                /*
                ISimpleFillSymbol pSimpleFillSymbol;
                IRgbColor pRgbColor;
                IRubberBand pRubberBand;
                IPolygon pPolygon;
                pSimpleFillSymbol = new SimpleFillSymbolClass();
                pRgbColor = new RgbColorClass();
                pRgbColor.Red = pcolor.R;//颜色
                pRgbColor.Green = pcolor.G;
                pRgbColor.Blue = pcolor.B;
                pSimpleFillSymbol.Color = pRgbColor;
                pRubberBand = new RubberPolygonClass();
                pPolygon = pRubberBand.TrackNew(axMapControl1.ActiveView.ScreenDisplay, pSimpleFillSymbol as ISymbol) as IPolygon;
                axMapControl1.ActiveView.ScreenDisplay.StartDrawing(axMapControl1.ActiveView.ScreenDisplay.hDC, (short)esriScreenCache.esriNoScreenCache);
                axMapControl1.ActiveView.ScreenDisplay.SetSymbol(pSimpleFillSymbol as ISymbol);
                axMapControl1.ActiveView.ScreenDisplay.DrawPolygon(pPolygon);
                axMapControl1.ActiveView.ScreenDisplay.FinishDrawing();*/
            }
        }
        private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)//处理失败需要处理
        {
            //MessageBox.Show(MouseTool);
          if (MouseTool == "movemap")
            {
                MouseTool = "";
                axMapControl1.CurrentTool = null;//使当前的工具失效
                axMapControl1.MousePointer = ESRI.ArcGIS.Controls.esriControlsMousePointer.esriPointerDefault;//将当前鼠标指针恢复成默认
               // MessageBox.Show("鼠标抬起");
            }
        }
        /*漫游*/

        /*mapcontrol*/
        /************************************************/

        /************************************************/
        /*axTOCControl*/
        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {

        }
        private ILayer getSeletedLyr()
        {
            IBasicMap map = null;
            ILayer layer = null;
            object other = null;
            object index = null;
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;

            //对于没有确定返回值 因此使用此法
            axTOCControl1.GetSelectedItem(ref item, ref map, ref layer, ref other, ref index);

            return layer;
        }

        /*axTOCControl*/
        /************************************************/

        /***********************************/
        /**鹰眼**/
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)//右键菜单
        {

        }


        private void axMapControl1_OnMapReplaced_1(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            axMapControl2.Map = new MapClass();
            if (axMapControl1.LayerCount > 0)
            {
                for (int i = axMapControl1.Map.LayerCount - 1;i>=0 ; i--)
                {
                    axMapControl2.AddLayer(axMapControl1.get_Layer(i));
                }
                axMapControl2.Extent = axMapControl1.Extent;
            }

        }

        private void axMapControl2_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (axMapControl2.Map.LayerCount > 0)
            {
                if (e.button == 1)
                {
                    IPoint pPoint = new PointClass();
                    pPoint.PutCoords(e.mapX, e.mapY);
                    axMapControl1.CenterAt(pPoint);
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                }
                else if (e.button == 2)
                {
                    IEnvelope pEnv = axMapControl2.TrackRectangle();
                    axMapControl1.Extent = pEnv;
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                }
            }

        }

        private void axMapControl2_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            if (e.button == 1)
            {
                IPoint pPoint = new PointClass();
                pPoint.PutCoords(e.mapX, e.mapY);
                axMapControl1.CenterAt(pPoint);
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }

        }

        private void axMapControl1_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            IEnvelope pEnvelope = (IEnvelope)e.newEnvelope;
            IGraphicsContainer pGraphicsContainer = axMapControl2.Map as IGraphicsContainer;
            IActiveView pActiveView = pGraphicsContainer as IActiveView;
            pGraphicsContainer.DeleteAllElements();
            IRectangleElement pRectangleEle = new RectangleElementClass();
            IElement pElement = pRectangleEle as IElement;
            pElement.Geometry = pEnvelope;

            IRgbColor pColor = new RgbColorClass();
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 255;

            ILineSymbol pOutline = new SimpleLineSymbolClass();
            pOutline.Width = 3;
            pOutline.Color = pColor;
            pColor = new RgbColorClass();
            pColor.Red = 255;
            pColor.Green = 0;
            pColor.Blue = 0;
            pColor.Transparency = 0;

            IFillSymbol pFillSymbol = new SimpleFillSymbolClass();
            pFillSymbol.Color = pColor;
            pFillSymbol.Outline = pOutline;
            IFillShapeElement pFillShapeEle = pElement as IFillShapeElement;
            pFillShapeEle.Symbol = pFillSymbol;
            pGraphicsContainer.AddElement((IElement)pFillShapeEle, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

        private void pointsToLineToolStripMenuItem_Click(object sender, EventArgs e)
        {




            int layer = (int)selectlayer[toolStripComboBox9.Text];
            IFeatureLayer pFeatLyr = axMapControl1.get_Layer(layer) as IFeatureLayer;

           


            IPolyline polyline = new PolylineClass();
            IFeatureClass pfeaturepoint = pFeatLyr.FeatureClass;

            IPointCollection pointColl = polyline as IPointCollection;

            for (int i = 0; i < pfeaturepoint.FeatureCount(null); i++)
            {
                IFeature pFeature = pfeaturepoint.GetFeature(i);

                IPoint point = pFeature.Shape as IPoint;

                //MessageBox.Show(point.X.ToString()+" "+ point.Y.ToString());

                pointColl.AddPoint(point);

                pFeature.Store();
            }

            //MessageBox.Show(pointColl.PointCount.ToString());


            IPolyline pPolyline = pointColl as IPolyline;

            //  IGeometry pGeometryPolyline = pPolyline as IGeometry;

            /*SimpleLineSymbol pSimpleLineSymbol;
            IRgbColor pRgbColor;
            pSimpleLineSymbol = new SimpleLineSymbolClass();
            pRgbColor = new RgbColorClass();
            pSimpleLineSymbol.Width = pSize;
            pRgbColor.Red = pcolor.R;//颜色
            pRgbColor.Green = pcolor.G;
            pRgbColor.Blue = pcolor.B;
            pSimpleLineSymbol.Color = pRgbColor;

                */
            // IGeometry ipolyline = pointColl as IGeometry;

            // ILineElement pLineElement;
            // pLineElement = new LineElementClass();
            // pLineElement.Symbol = pSimpleLineSymbol;
            // IElement pElement;
            // pElement = pLineElement as IElement;
            // pElement.Geometry = ipolyline;
            //IGraphicsContainer pGraphicsContainer = axMapControl1.ActiveView.FocusMap as IGraphicsContainer;
            // pGraphicsContainer.AddElement((IElement)pLineElement, 0);
            //axMapControl1.ActiveView.Refresh();


            IGeoDataset in_GeoDataset = pFeatLyr.FeatureClass as IGeoDataset;
            ISpatialReference in_SpatialReference = in_GeoDataset.SpatialReference;
            IFeatureClass out_FeatureClass = CreateShapefile(in_SpatialReference);
            IFeatureBuffer out_FeatureBuffer = out_FeatureClass.CreateFeatureBuffer();
            IFeatureCursor out_FeatureCursor = out_FeatureClass.Insert(true);
            out_FeatureBuffer.Shape = pPolyline;
            out_FeatureCursor.InsertFeature(out_FeatureBuffer);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(out_FeatureCursor);


            axMapControl1.AddShapeFile(System.IO.Path.GetDirectoryName(out_filePath), System.IO.Path.GetFileName(out_filePath));
            axMapControl1.Refresh();
        }
        private IFeatureClass CreateShapefile(ISpatialReference pSpatialReference)
        {
            IGeometryDef pGeometryDef = new GeometryDef();
            IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
            pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
            pGeometryDefEdit.HasM_2 = false;
            pGeometryDefEdit.HasZ_2 = false;
            pGeometryDefEdit.SpatialReference_2 = pSpatialReference;

            // 字段集合
            IFields pFields = new Fields();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;

            // Shape
            IField pField = new Field();
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldEdit.GeometryDef_2 = pGeometryDef;
            pFieldEdit.AliasName_2 = "Shape";
            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.IsNullable_2 = false;
            pFieldEdit.Required_2 = true;
            pFieldsEdit.AddField(pField);

            // 创建shp
            

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "输出文件";
            saveFileDialog.Filter = "Shapefile(*.shp)|*.shp";
            saveFileDialog.OverwritePrompt = true;
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                out_filePath = saveFileDialog.FileName;
               
            }

          
           IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(out_filePath), 0);
            IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            IFeatureClass pFeatureClass = pFeatureWorkspace.CreateFeatureClass(System.IO.Path.GetFileName(out_filePath), pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
            return pFeatureClass;
        }

        private void toolStripComboBox10_Click(object sender, EventArgs e)
        {
            Paster_selectlayer.Clear();
            toolStripComboBox10.Items.Clear();
            int layernum = axMapControl1.LayerCount;
            for (int i = 0; i < layernum; i++)
            {
                IRasterLayer pRasterLayer;

               pRasterLayer = axMapControl1.Map.get_Layer(i) as IRasterLayer;
                if (pRasterLayer != null)
                {
                    string str = axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name;
                    toolStripComboBox10.Items.Add(str);

                    Paster_selectlayer.Add(str, i);
                }

                //LayertoNum.Add(axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name, i);
            }
        }

        private void toolStripComboBox11_Click(object sender, EventArgs e)
        {
            selectlayer.Clear();
            toolStripComboBox11.Items.Clear();
            int layernum = axMapControl1.LayerCount;
            for (int i = 0; i < layernum; i++)
            {
                IFeatureLayer pFeatureLayer;

                pFeatureLayer = axMapControl1.Map.get_Layer(i) as IFeatureLayer;
                if (pFeatureLayer != null&&pFeatureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    string str = axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name;
                    toolStripComboBox11.Items.Add(str);

                    selectlayer.Add(str, i);
                }

                //LayertoNum.Add(axTOCControl1.ActiveView.FocusMap.get_Layer(i).Name, i);
            }
        }

        private void 开始裁剪ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int layer = (int)selectlayer[toolStripComboBox11.Text];
           
            IFeatureLayer pFeatureLayer = axMapControl1.get_Layer(layer) as IFeatureLayer;//输入裁剪矢量图层
             layer = (int)Paster_selectlayer[toolStripComboBox10.Text];
            IRasterLayer pRasterLayer = axMapControl1.get_Layer(layer) as IRasterLayer;//输入裁剪栅格图层
            //IGeometry geometry = getBasicGeometry_polygon(pFeatureLayer.FeatureClass);
            IPolygon pPoly = pFeatureLayer.FeatureClass.GetFeature(0).Shape as IPolygon;//设置裁剪要素
            rasterClip(pRasterLayer, pPoly, "rasterClip0");//调用裁剪方法
                                                           //强提醒，完成裁剪
            MessageBox.Show("裁剪完成！");

        }
        private IGeometry getBasicGeometry_polygon(IFeatureClass pFeatureClass)
        {
            var pFeatureCursor = pFeatureClass.Search(null, false);
            var pF = pFeatureCursor.NextFeature();
            IGeometry pUnionGeo = new PolygonClass();
            pUnionGeo = pF.Shape;
            while (pF != null)
            {
                var pUnionTopo = pUnionGeo as ITopologicalOperator;
                pUnionGeo = pUnionTopo.Union(pF.Shape);
                pF = pFeatureCursor.NextFeature();
            }
            return pUnionGeo;
        }


        public void rasterClip(IRasterLayer pRasterLayer, IPolygon clipGeo, string FileName)
        {
            IRaster pRaster = pRasterLayer.Raster;//获取栅格文件
            IRasterProps pProps = pRaster as IRasterProps;
            object cellSizeProvider = pProps.MeanCellSize().X;
            IGeoDataset pInputDataset = pRaster as IGeoDataset;
            IExtractionOp pExtractionOp = new RasterExtractionOp() as IExtractionOp;
            IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;
            pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);
            object extentProvider = clipGeo.Envelope;//获取矢量图形范围
            object snapRasterData = Type.Missing;
            pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
            IGeoDataset pOutputDataset = pExtractionOp.Polygon(pInputDataset, clipGeo as IPolygon, true);
            IRaster clipRaster;  //裁切后得到的IRaster
            if (pOutputDataset is IRasterLayer)
            {
                IRasterLayer rasterLayer = pOutputDataset as IRasterLayer;
                clipRaster = rasterLayer.Raster;
            }
            else if (pOutputDataset is IRasterDataset)
            {
                IRasterDataset rasterDataset = pOutputDataset as IRasterDataset;
                clipRaster = rasterDataset.CreateDefaultRaster();
            }
            else if (pOutputDataset is IRaster)
            {
                clipRaster = pOutputDataset as IRaster;
            }
            else
            {
                return;
            }
            /*
            IRasterLayer outRasterLayer2 = new RasterLayerClass();
            IRasterBandCollection myRasterBandCollection = clipRaster as IRasterBandCollection;
            for (int i = 0; i < 3; i++)
            {
                IRasterBand myRasterBand = myRasterBandCollection.Item(i);


                IRasterDataset myRasterDataset = myRasterBand as IRasterDataset;

               

                outRasterLayer2.CreateFromDataset(myRasterDataset);
            }
             axMapControl1.Map.AddLayer(outRasterLayer2 as ILayer); ;
           */

            //保存裁切后得到的clipRaster,直接保存为tif影像文件
            IWorkspaceFactory pWKSF = new RasterWorkspaceFactory();
            //保存裁剪后的影像到本地路径下
            //string filepath = @"F:\临时\";
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "输出文件";
            saveFileDialog.Filter = "Shapefile(*.tif)|*.tif";
            saveFileDialog.OverwritePrompt = true;
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                out_filePath = saveFileDialog.FileName;

            }

            //判断文件夹是否存在，如果不存在新建文件夹
            if (false == System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(out_filePath)))
            {
                //创建文件夹
                Directory.CreateDirectory(System.IO.Path.GetDirectoryName(out_filePath));
            }
            IWorkspace pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(out_filePath), 0);
            ISaveAs pSaveAs = clipRaster as ISaveAs;
            //输出要素类的名称，文件后缀可以设置
            
            


            pSaveAs.SaveAs(System.IO.Path.GetFileName(out_filePath), pWorkspace, "TIFF");
            

            IRasterLayer outRasterLayer = new RasterLayerClass();

            outRasterLayer.CreateFromDataset(OpenFileRasterDataset(System.IO.Path.GetDirectoryName(out_filePath),System.IO.Path.GetFileName(out_filePath)));
            //MessageBox.Show(out_filePath);

            axMapControl1.Map.AddLayer(outRasterLayer);

        }
        static IRasterDataset OpenFileRasterDataset(string folderName, string datasetName)
        {
            //Open a raster file workspace.
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory();
            IRasterWorkspace rasterWorkspace = (IRasterWorkspace)
                workspaceFactory.OpenFromFile(folderName, 0);

            //Open a file raster dataset. 
            IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(datasetName);
            return rasterDataset;
        }





        /*鹰眼*/
        /******************************/



    }
}
